/**
* Author: fulishang
* Create Time  : 2016年8月4日,下午11:12:28
* Modify Time :
* Desc  : 
*/
package com.sam.si.file.filter;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.integration.file.filters.AbstractFileListFilter;

import com.sam.si.file.util.Constants;

public class FileFilter extends AbstractFileListFilter<File>{

	private static final Logger LOGGER = Logger.getLogger(FileFilter.class);
	
	private final Map<String, Long> files = new HashMap<>();
	private final Object monitor = new Object();

	@Override
	protected boolean accept(File file) {
		synchronized (this.monitor) {
			return this.filterBySuffix(file) && this.filterByModifyTime(file);
		}
	}
	
	/**
	 * filter file by suffix
	 * @param file
	 * @return boolean filesuffix acceptable
	 */
	private boolean filterBySuffix(File file) {
		boolean isSuffixAccept = false;
		String fileName = file.getName();
		String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		
		for (int i=0; i<Constants.ACCEPTABLE_FILE_PATTERN.length; i++) {
			if (fileSuffix.equals(Constants.ACCEPTABLE_FILE_PATTERN[i])){
				isSuffixAccept = true;
			}
		}
		LOGGER.info("The suffix - " + fileSuffix + " is " + (isSuffixAccept?"Acceptable":"Unacceptable"));
		return isSuffixAccept;
	}
	
	/**
	 * filter file by modified time
	 * @param file
	 * @return boolean file is new
	 */
	private boolean filterByModifyTime(File file) {
		boolean isNew = false;
		Long previousModifiedTime = files.put(file.getName(), file.lastModified());
		LOGGER.info("File previous Modified Time is " + previousModifiedTime);
		isNew = previousModifiedTime == null || previousModifiedTime != file.lastModified();
		LOGGER.info("Current file is - " + (isNew?"NEW":"OLD"));
		return isNew;
	}
}
